<template>
  <div class="enterInformation" :style="{ background: `url(${imgbgc})`, 'background-size': '100% 100%' }">
    <div class="innerBox">
      <div class="content">
        <div class="contInner">
          <el-page-header :icon="null" @back="goBack">
            <template #title>
              <el-icon><ArrowLeftBold /></el-icon>
              <span class="returnClass">返回</span>
            </template>
            <template #content>
            </template>
          </el-page-header>
          <div class="title">基本信息</div>
          <el-scrollbar>
            <el-form
              :model="formInfo"
              :rules="rules"
              ref="formInfo"
              label-width="120px"
            >
              <el-form-item label="姓名" prop="name">
                <el-input :disabled='type=="edit"'
                  v-model="formInfo.name"
                  placeholder="请输入姓名"
                />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formInfo.sex" :disabled='type=="edit"'>
                  <el-radio :label="'0'">男</el-radio>
                  <el-radio :label="'1'">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="身体状况" v-if="personType=='child'" prop="health">
                <el-radio-group v-model="formInfo.health" :disabled='disableFlag'>
                  <el-radio :label="'0'">健康</el-radio>
                  <el-radio :label="'1'">疾患</el-radio>
                </el-radio-group>
                <el-input v-if="formInfo.health=='1'" style="width: 253px;margin-left: 14px;" v-model="formInfo.sickName" placeholder="请输入疾患名称"/>
              </el-form-item>
              <el-form-item label="联系电话" :disabled='disableFlag' prop="phone">
                <el-input
                  v-model="formInfo.phone"
                  placeholder="请输入联系电话"
                />
              </el-form-item>
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  :disabled='type=="edit"'
                  v-model="formInfo.birthday"
                  type="date"
                  placeholder="请输入出生日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="职业" v-if="personType=='adult'" prop="occupation">
                <el-input
                  v-model="formInfo.occupation"
                  placeholder="请输入职业"
                />
              </el-form-item>
              <el-form-item label="学历" v-if="personType=='adult'" prop="education">
                <el-input
                  v-model="formInfo.education"
                  placeholder="请输入学历"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formInfo.email"
                  placeholder="请输入邮箱"
                />
              </el-form-item>
              <el-form-item label="所在地区">
                <el-input
                  v-model="formInfo.address"
                  placeholder="请输入所在地区"
                />
              </el-form-item>
              <el-form-item label="民族">
                <el-input
                  v-model="formInfo.race"
                  placeholder="请输入民族"
                />
              </el-form-item>
              <el-form-item label="性格特点">
                <el-input
                  v-model="formInfo.character"
                  placeholder="请输入性格特点"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" v-show="type=='add'" @click="nextFn('formInfo')">下一步</el-button>
                <el-button type="primary" v-show="type=='edit'" @click="nextFn('formInfo')">保存</el-button>
              </el-form-item>
            </el-form>
          </el-scrollbar>
        </div>
      </div>
      <div class="rightBox" v-if="personType=='child'">
        <img v-if="formInfo.sex=='1'" src="@/assets/images/c3.jpg" alt="">
        <img v-else src="@/assets/images/c4.jpg" alt="">
      </div>
      <div class="rightBox" v-else>
        <img v-if="formInfo.sex=='1'" style="width: auto;" src="@/assets/images/p1.png" alt="">
        <img v-else style="width: auto;" src="@/assets/images/p6.png" alt="">
      </div>
    </div>
  </div>
</template>

<script>
import { testedAddBaseInfo, testedUpdateBaseInfo, userGetApiToken } from '@/api/home.js'
export default {
  data() {
    return {
      imgbgc: require('../assets/images/pbgc.jpg'),
      personType: 'adult',
      type: 'add',
      // sex 0男 1女；classification 0儿童 1成人
      formInfo: {},
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        health: [
          { required: true, message: '请选择身体状况', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        classification: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        birthday: [
          { type: 'date', required: true, message: '请输入出生日期', trigger: 'change' }
        ],
        occupation: [
          { required: true, message: '请输入职业', trigger: 'blur' }
        ],
        education: [
          { required: true, message: '请输入学历', trigger: 'blur' }
        ]
      },
      disableFlag: false,
      WAIMS_TOKEN: '',
      selectType: 1,
      numSurplus: null,
    };
  },
  methods: {
    goBack() {
      this.$router.push({
        path: '/testList'
      })
    },
    nextFn(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 需要判断是新增还是编辑
          this.formInfo.classification = this.personType == 'adult' ? '1' : '0';
          let ageIsAdult = this.isEighteenYearsOld(this.formInfo.birthday);
          if (this.personType === 'adult' && !ageIsAdult) {
            this.$message({
              message: '出生日期未成年'
            })
            return;
          } else if (this.personType !== 'adult' && ageIsAdult) {
            this.$message({
              message: '出生日期已成年'
            })
            return;
          }
          if(this.type === 'add') {
            this.confirmnfoFn()
          } else {
            this.confirmnfo4EditFn()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    confirmnfoFn() {
      var query = {
        json: JSON.stringify(this.formInfo),
        API_TOKEN: localStorage.getItem('token'),
        WAIMS_TOKEN: this.WAIMS_TOKEN
        // testId: 10008
      }
      testedAddBaseInfo(query).then(res => {
        console.log(res)
        if(res.code === 200) {
          sessionStorage.setItem('testedId', res.data)
          // 姓名 出生日期 电话
          sessionStorage.setItem('name', this.formInfo.name)
          sessionStorage.setItem('birthday', this.formInfo.birthday)
          sessionStorage.setItem('phone', this.formInfo.phone)
          sessionStorage.setItem('health', this.formInfo.health) // health 0:健康  1:疾患
          let path;
          if (this.personType !== 'adult') {
            if (this.numSurplus.lowSurplus == 0) {
              path = '/testList';
            } else {
              path = '/selection';
            }
          } else {
            if (this.numSurplus.heightSurplus == 0) {
              path = '/testList';
            } else {
              path = '/selection4adult';
            }
          }
          this.$router.push({
            path: path,
            query: {
              selectType: this.selectType
            }
          })
        }
      }).catch(err => {
        console.log(err)
        this.$message({
          message: '已存在该被试'
        })
        this.getTokenFn()
      })
    },
    confirmnfo4EditFn() {
      var query = {
        json: JSON.stringify(this.formInfo),
        WAIMS_TOKEN: this.WAIMS_TOKEN
        // testId: 10008
      }
      testedUpdateBaseInfo(query).then(res => {
        if(res.code === 200) {
          // 姓名 出生日期 电话
        sessionStorage.setItem('name', this.formInfo.name)
        sessionStorage.setItem('birthday', this.formInfo.birthday)
        sessionStorage.setItem('phone', this.formInfo.phone)
        sessionStorage.setItem('health', this.formInfo.health)
          this.$router.push({
            path: '/testList'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getTokenFn() {
      userGetApiToken().then(res => {
        if(res.code === 200) {
          localStorage.setItem('token', res.data)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    isEighteenYearsOld(birthDate) {
      // 将生日转换为日期对象
      let today = new Date();
      let dob = new Date(birthDate);
      // 计算年龄差
      let ageDiff = today.getFullYear() - dob.getFullYear();
      // 如果生日还没过，减少一岁
      if (today.getMonth() < dob.getMonth() || (today.getMonth() === dob.getMonth() && today.getDate() < dob.getDate())) {
        ageDiff--;
      }
      // 判断是否满足18岁
      return ageDiff >= 18;
    },
  },
  mounted() {
    if(localStorage.getItem('WAIMS_TOKEN') && localStorage.getItem('WAIMS_TOKEN') !== '') {
      this.WAIMS_TOKEN = localStorage.getItem('WAIMS_TOKEN')
      this.type = this.$route.query.type ? this.$route.query.type : 'add'
      this.formInfo = this.$route.query.formInfo ? JSON.parse(this.$route.query.formInfo) : {}
      this.formInfo.classification = this.formInfo.classification.toString()
      this.formInfo.sex = this.formInfo.sex.toString()
      this.formInfo.health = this.formInfo.health.toString()
      this.selectType = this.$route.query.selectType ? this.$route.query.selectType : 1
      this.numSurplus = this.$route.query.numSurplus ? JSON.parse(this.$route.query.numSurplus) : {}
      this.getTokenFn()
    } else {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
    this.personType = sessionStorage.getItem('personType')
    if(this.personType == 'adult') {
      this.imgbgc = require('../assets/images/pbgc.jpg')
    } else {
      this.imgbgc = require('../assets/images/cbgc.jpg')
    }
  }
};
</script>
<style lang="scss" scoped>
.enterInformation {
  height: calc(100vh - 200px);
  background: url(../assets/images/pbgc.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 100px 140px;
  .innerBox {
    height: calc(100% - 80px);
    padding: 40px 20px;
    background-color: #ffffff;
    box-shadow: 35px 35px 50px 0px
      rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
  }
  .content {
    width: 45%;
    // display: flex;
    // padding: 10px 80px 0px 100px;
    padding: 10px 5% 0 2%;
    .contInner {
      height: calc(100% - 50px);
    }
  }
  .rightBox {
    width: 55%;
    padding: 20px;
    // display: flex;
    // padding: 80px 150px 80px 0px;
    img {
      width: 95%;
      height: 100%;
    }
  }
  .title {
    font-size: 36px;
    font-weight: 700;
    margin-bottom: 30px;
    color: #009fb5;
  }
}
</style>

<style lang="scss">
.enterInformation {
  .el-input {
    width: 400px;
  }
  .el-button {
    margin-left: 103px;
  }
  .el-radio.is-bordered.is-checked, .el-radio__inner:hover {
    border-color: #009fb5;
  }
  .el-radio__input.is-checked .el-radio__inner {
    background-color: #009fb5;
    border-color: #009fb5;
  }
  .el-radio__input.is-checked+.el-radio__label {
    color: #009fb5;
  }
  .el-divider--vertical {
    border-left: 0;
  }
  .el-page-header__title {
    .el-icon {
      padding: 4px;
      background: #2b82e7;
      color: #fff;
      border-radius: 50%;
    }
    .returnClass {
      font-size: 16px;
      font-weight: 700;
      margin-left: 10px;
      vertical-align: text-bottom;
    }
  }
}
</style>
